package com.garlic.face.jlf.transaction.balance;

import android.content.Context;
import android.content.SharedPreferences;


import com.garlic.face.jlf.App;
import com.garlic.face.jlf.transaction.Means;

import java.io.File;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortFinder;

import static android.content.Context.MODE_PRIVATE;


public class SerialPortFunction {
    private  volatile  static   SerialPortFunction serialPortFunction;
    private  ReadSerialPort readSerialPort;
    private ExecutorService executorService;

    private Context context;
    private SerialPort eleSerial;
    private SerialPort lightSerial;
    //双重锁定 避免多线程情况下发生错误
    public static SerialPortFunction getInstance(){
        if (serialPortFunction==null){
            synchronized (SerialPortFunction.class){
                if (serialPortFunction==null){
                    serialPortFunction=new SerialPortFunction();
                }
            }
        }
        return serialPortFunction;
    }

    private SerialPortFunction(){
        executorService= Executors.newFixedThreadPool(3);
    }

    public void setContext(Context context) {
        this.context = context;
    }


    public void startSerialReadEle( ReadSerialPort.DataWeight dataWeight){
        if (eleSerial==null){
            try {
                eleSerial=getSerialPort("scale");
                Means.blScaleOK = true;
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
                Means.blScaleOK = false;
            }
        }

        readSerialPort=new ReadSerialPort(eleSerial);
        readSerialPort.setDataWeight(dataWeight);
        executorService.submit(readSerialPort);
    }

    public void sendEle(final byte[] data){
        Runnable ele = () -> {
            if (eleSerial==null){
                try {
                    eleSerial=getSerialPort("scale");
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                eleSerial.getOutputStream().write(data);
                eleSerial.getOutputStream().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
        executorService.submit(ele);
    }

    public void sendEle(final String command){
        Runnable ele = () -> {
            if (eleSerial==null){
                try {
                    eleSerial=getSerialPort("scale");
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                eleSerial.getOutputStream().write(Util.toBytes(command));
                eleSerial.getOutputStream().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
        executorService.submit(ele);
    }

    public void sendLight(final String conmand){
        Runnable runnable = () -> {
            if (lightSerial==null){
                try {
                    lightSerial=getSerialPort("light");
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                lightSerial.getOutputStream().write(Util.toBytes(conmand));
                lightSerial.getOutputStream().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        };
        executorService.submit(runnable);
    }

    public void closeEle(){
        if (readSerialPort!=null){
            readSerialPort.isEixt=true;
            readSerialPort=null;
        }
        if (eleSerial!=null){
            eleSerial=null;
        }
    }
    public  void closeLight(){
        if (lightSerial!=null){
            lightSerial=null;
        }
    }


    private SerialPort getSerialPort(String devicesName) throws SecurityException, IOException, InvalidParameterException, InterruptedException {
            /* Read serial port parameters */
        String path = "";
        int baudrate = 0;
        String packageName = App.getContext().getPackageName();
        if (devicesName.equals("scale")) {
            //电子称的
            SharedPreferences sp = context.getSharedPreferences(packageName+"_preferences", MODE_PRIVATE);
            path = sp.getString("scale_serial", "/dev/ttyS1");
            String test = sp.getString("bag_small", "");
            baudrate = Integer.decode(sp.getString("scale_baudrates", "9600"));
            //path = "/dev/ttyS4";

        } else if(devicesName.equals("light")) {
            //灯的
            SharedPreferences sp = context.getSharedPreferences(packageName+"_preferences", MODE_PRIVATE);
            path = sp.getString("light_serial", "/dev/ttyS3");
            baudrate = Integer.decode(sp.getString("light_baudrates", "9600"));
            //path = "/dev/ttyS3";
        }
        System.out.println("SerialPortFunction  devicesName:" + devicesName + "串口 "+path+ "波特率  :"+baudrate);
            /* Check parameters */
        if ( (path.length() == 0) || (baudrate == -1)) {
            throw new InvalidParameterException();
        }

        return  new SerialPort(new File(path), baudrate, 0);
    }
}
